<?php
header("Content-type: text/html; charset=utf-8");
ini_set('display_errors', '1');
include_once "function.php";
include_once "../func.php";


$code = $_GET['code'];
$state = $_GET['state'];

$from = 'user';
if(isset($_GET['from'])){
   $from = $_GET['from'];
}
$base_uri = "http://www.xunlianri.com/index.php/profile?from=wx";
if($from == 'coach'){
	$base_uri = "http://www.xunlianri.com/index.php/profile?from=coach";
	//$base_uri = "http://www.xunlianri.com/index.php/coach/reg?from=wx";
}


//获取open
$access_json = wxoauth2_request_openid($code);

$access = json_decode($access_json , true);
$access_token = $access['access_token'];
$openid = $access['openid'];

//判断是什么类型 



if($access['scope'] == 'snsapi_base'){
	$base_uri = $base_uri.'&openid='.$openid;
  
	header("location: $base_uri");
	exit;
}

 
$userinfo_json = wxoauth2_request_userinfo($access_token,$openid);
$userinfo = json_decode($userinfo_json , true);
 
//print_r($userinfo);
//获得了用户数据 根据openid 更新用户资料
$nickname = $userinfo['nickname'];
$thumb_src = $userinfo['headimgurl'];
$sex = $userinfo['sex'];
$province = $userinfo['province'];
$city = $userinfo['city'];
$country = $userinfo['country'];

//$phonenumber = $_GET['phonenumber'];
$sql = "select * from phonenumber where wx_openid='$openid' order by id desc";
$pn = $db->get_row($sql);
$phonenumber = $pn->phonenumber;

$sql = "insert into member(nickname,wx_openid,thumb,phonenumber,createtime,wx_province,wx_city,wx_country) values('$nickname','$openid','$thumb_src','$phonenumber',NOW(),'$province','$city','$country')";
$db->query($sql);

//$base_uri = $base_uri."&openid=".$openid."&state=".$state."&nickname=".$nickname."&thumb=".$thumb_src;

$base_uri = $base_uri."&openid=".$openid;
header("location: ".$base_uri);
exit;

?>